import sys

from PySide6.QtCore import QSortFilterProxyModel, Signal

from backend.db.database import SessionLocal
from backend.schemas.member_pydantic import MemberCreate
from backend.services.consumption_services import ConsumptionService
from backend.services.members_service import MemberService
from front.models.member_list_model import UserTableModel, ConsumptionButtonDelegate
from front.ui.ui_consump_dialog import Ui_Dialog
from front.ui.ui_vip_list import Ui_Frame
from PySide6.QtWidgets import QApplication, QFrame, QHeaderView, QDialog, QMessageBox

from front.ui_logic.change_vip import ChangeVip
from front.ui_logic.delete_vip import DeleteVip
from front.ui_logic.recharge_dialog import RechargeDialog
from front.ui_logic.register import Register


def check_windows(cla):
    """检查窗口是否存在"""
    if cla:
        cla.close()
        cla.deleteLater()


class VipList(QFrame, Ui_Frame):
    def __init__(self, parent=None, ):
        super().__init__(parent)
        self.delete_window = None
        self.update_vip = None
        self.recharge_amount = None
        self.add_window = None
        self.consumption_dialog = None
        self.setupUi(self)
        self.changeMemberButton.clicked.connect(self.change_vip)
        self.rechargeAmountButton.clicked.connect(self.recharge_vip)
        self.addMemberButton.clicked.connect(self.connect_member_window)
        self.delete_vipButton.clicked.connect(self.delete_vip)

    def set_table_view(self, data):
        data = [i.model_dump() for i in data]
        """设置tableview"""
        self.model = UserTableModel(data)
        self.proxy_model = QSortFilterProxyModel()
        self.proxy_model.setSourceModel(self.model)
        self.tableView.setModel(self.proxy_model)
        self.tableView.setSortingEnabled(True)
        self.tableView.resizeColumnsToContents()
        header = self.tableView.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.Stretch)
        header.setSectionResizeMode(5, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(9, QHeaderView.ResizeToContents)
        self.create_member_tableview_button()

    def connect_vip_button(self, callback_func):
        """跟消费按钮连接"""
        delegate = ConsumptionButtonDelegate()
        delegate.consume_callback = callback_func  # ← 绑定点击后执行的函数
        self.tableView.setItemDelegate(delegate)

    def create_member_tableview_button(self):
        """填充消费按钮以及功能"""
        self.connect_vip_button(self.clicked_consumption_button)

    def clicked_consumption_button(self, row: int):
        """消费按钮点击后的处理逻辑"""
        model = self.proxy_model
        if model is None:
            return

        # 获取该行数据（假设第0列是ID，第1列是姓名）
        user_id = model.index(row, 0).data()
        user_name = model.index(row, 2).data()
        print(f"为用户 {user_name} (ID: {user_id}) 创建消费记录")
        self.show_consumption_message(user_id)

    def show_consumption_message(self, id_value):
        """消费按钮函数"""

        class ConsumptionMessage(QDialog, Ui_Dialog):
            consumption_value = Signal(dict)

            def __init__(self, parent=None, ):
                super().__init__(parent)
                self.setupUi(self)
                self.pushButton.clicked.connect(self.confirm_consumption)
                self.doubleSpinBox.setRange(0, 10000)

            def get_value(self):
                amount = self.doubleSpinBox.value()
                description = self.lineEdit_3.text()
                # 这里可以添加数据验证逻辑，比如金额范围等
                if amount < 0:
                    raise ValueError("金额不能为负数")
                return {'member_id': id_value,
                        'amount': float(amount),
                        'description': description}

            def confirm_consumption(self):
                a = self.get_value()
                self.consumption_value.emit(a)
                self.close()

        if self.consumption_dialog:
            self.consumption_dialog.deleteLater()  # 释放资源
        self.consumption_dialog = ConsumptionMessage(self)
        self.consumption_dialog.consumption_value.connect(self.create_a_consumption_record)
        self.consumption_dialog.show()

    def create_a_consumption_record(self, data: dict):
        """发送创建交易记录请求"""

        try:
            with SessionLocal() as session:
                consumption_service = ConsumptionService(session)
                consumption_service.add_consumption(**data)
            QMessageBox.information(self, "成功", "消费记录登记成功")
            self.get_member_information()
        except Exception as e:
            print(e)
            QMessageBox.warning(self, "失败", "余额不足")

        # 获得单独客户信息

    def get_member_information(self, value=None):
        """获取会员信息"""
        with SessionLocal() as session:
            consumption_service = MemberService(session)
            a = consumption_service.all_get_members(value)
        print(a)
        self.set_table_view(a)

    def change_vip(self):
        check_windows(self.update_vip)
        self.update_vip = ChangeVip(self)
        self.update_vip.refresh.connect(self.get_member_information)
        self.update_vip.show()

    def recharge_vip(self):
        check_windows(self.recharge_amount)
        self.recharge_amount = RechargeDialog(self)
        self.recharge_amount.refresh.connect(self.get_member_information)
        self.recharge_amount.show()

    # 创建会员窗口
    def connect_member_window(self):
        """连接会员创建窗口"""
        check_windows(self.add_window)
        self.add_window = Register(self)
        self.add_window.refresh.connect(self.get_member_information)
        self.add_window.show()

    ####删除会员
    def delete_vip(self):
        check_windows(self.delete_window)
        self.delete_window=DeleteVip(self)
        self.delete_window.refresh.connect(self.get_member_information)
        self.delete_window.show()

if __name__ == '__main__':
    app = QApplication([])
    with SessionLocal() as session:
        a = MemberService(session)
        b = a.all_get_members()
    win = VipList()
    win.set_table_view(b)
    win.show()
    sys.exit(app.exec())
